﻿package game.errors {
	import flash.utils.setTimeout;
	import flash.events.Event;
	import flash.geom.Rectangle;
	import flash.events.MouseEvent;
	import game.ui.Text;
	import game.ui.Button;
	import game.ui.DynamicClip;
	import game.objects.DynamicObject;
	import game.debug.Debug;
	
	public class GameError extends DynamicClip {
		
		public static const SOCKET_ERROR:String	= 'SE';
		public static const DATA_ERROR:String	= 'DE';
		public static const INIT_ERROR:String	= 'IE';
		public static const GAME_ERROR:String	= 'GE';
		
		private var ENABLED:Boolean = false;
		
		private function get btnClose():Button	{ return getChildByName('btnClose') as Button; }
		private function get header():Text		{ return getChildByName('header') as Text; }
		private function get text():Text		{ return getChildByName('text') as Text; }
		private function get sub():Text			{ return getChildByName('sub') as Text; }
		
		public function GameError(type:String, code:Number, string:String = "", params:Object = null):void {
			/*
				type - тип ошибки
					SE - ошибки связанные с соединением
					DE - ошибки с сервера
					IE - ошибки инициализации
					GE - ошибки игры
				code - код ошибки
			*/
			
			var skin:DynamicObject = config.getSkin(DynamicObject.ERROR);
			
			super(skin);
			
			if (!skin) {
				Debug.log('Ошибка ['+type+'], код: '+code+', текст: '+string, Debug.INTERFACE);
				return;
			}
			
			back.alpha = 0.8;
			
			if (header) {
				header.set		('IDS_ERROR_'+type, {type: type, code: code});
			}
			
			if (text) {
				text.set		('IDS_'+type+'_'+String(code), {code: code});
			}
			
			if (sub) {
				sub.set			(string, params, false);
			}
			
			switch (type) {
				case GameError.SOCKET_ERROR:
					ENABLED = true;
				break;
				case GameError.INIT_ERROR:
					ENABLED = true;
				break;
				case GameError.DATA_ERROR:
					
				break;
			}
			
			if (btnClose) {
				if (ENABLED)
					btnClose.enabled = false;
				else
					btnClose.addEventListener(MouseEvent.CLICK, closeHandler);
			}
			
			
			this.addEventListener(Event.ADDED_TO_STAGE, added);
			
		}
		
		private function closeHandler(event:MouseEvent):void {
			close();
		}
		
		private function hide():void {
			this.visible = false;
		}
		
		private function added(event:Event):void {
			
			if (!ENABLED)
				setTimeout(close, config.hideRemoveSecs*1000);
		}
		
	}
	
}